package com.zian.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zian.domain.po.SysOrder;
import com.zian.enums.OrderStatusEnum;
import com.zian.enums.PayStatusEnum;
import com.zian.enums.PayTypeEnum;
import com.zian.exception.BizIllegalException;
import com.zian.mapper.SysOrderMapper;
import com.zian.service.IPayService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class PayServiceImpl implements IPayService {



    private final SysOrderMapper orderMapper;

    /**
     * 订单支付
     * @param orderNo
     * @return
     */
    @Override
    public String pay(String orderNo)  {
        SysOrder order = orderMapper.selectOne(Wrappers.<SysOrder>lambdaQuery().eq(SysOrder::getOrderNo, orderNo));
          if (order == null) {
          throw new BizIllegalException("订单不存在");
          }

        // 2. 发起支付宝预支付
        try {
            AlipayTradeAppPayResponse response = Factory.Payment.App().pay(order.getExtraInfo(),order.getOrderNo(), order.getTotalPrice().toString());
            if (response == null ){
                throw new BizIllegalException("支付失败");
            }
            String body = response.body;
            log.info("body:{}",body);
            return body;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 支付状态回调用
     * @param outTradeNo
     */
    @Override
    public void payNotify(String outTradeNo) {
        if (outTradeNo == null){
            throw new BizIllegalException("支付失败");
        }

        // 1.根据订单号查询订单
        SysOrder order = orderMapper.selectOne(Wrappers.<SysOrder>lambdaQuery().eq(SysOrder::getOrderNo, outTradeNo));
        if (order == null) {
            throw new BizIllegalException("订单不存在");
        }
        if (order.getPayStatus().equals(PayStatusEnum.SUCCESS)) throw new BizIllegalException("订单已支付");

        // 2. 修改订单状态
        order.setPayStatus(PayStatusEnum.SUCCESS);
        order.setPayType(PayTypeEnum.ALIPAY);
        order.setOrderStatus(OrderStatusEnum.PAID);
        order.setPayTime(LocalDateTime.now());
        int result = orderMapper.updateById(order);
        log.info("支付回调修改订单状态:{}",result);
        if (result <=0 ){
            throw new BizIllegalException("修改订单状态失败");
        }

    }

    /**
     * 订单退款
     * @param orderNo
     */
    @Override
    public String refund(String orderNo ,  String refundAmount) {
        try {
            // Factory.能力类别.场景类别.接口方法名称( ... )
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(orderNo, refundAmount);
            if (response.getTradeNo()== null) {
                 throw new BizIllegalException("退款失败");
            }
           return response.getTradeNo();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
